package com.gxc.graph;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 并查集
 */
public class UnionLooUpSet {

    private HashMap<Node, List<Node>> setMap;

    public UnionLooUpSet(List<Node> nodes) {
        for (Node node : nodes) {
            List<Node> list = new ArrayList<>();
            list.add(node);
            setMap.put(node, list);
        }
    }

    public boolean isSameSet(Node from, Node to) {
        List<Node> fromSet = setMap.get(from);
        List<Node> toSet = setMap.get(to);
        return fromSet==toSet;
    }

    public void unionSet(Node from, Node to) {
        List<Node> fromSet = setMap.get(from);
        List<Node> toSet = setMap.get(to);

        for (Node node : toSet) {
            fromSet.add(node);
            setMap.put(node, fromSet);
        }

    }

}
